import React, { useState } from 'react';
import { 
  Form, 
  Input, 
  Select, 
  Button, 
  Card, 
  message, 
  Upload, 
  Row, 
  Col,
  Spin
} from 'antd';
import { 
  PlusOutlined, 
  UploadOutlined, 
  CustomerServiceOutlined, 
  BugOutlined 
} from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import api from '../services/api';

const { TextArea } = Input;
const { Option } = Select;

const IssueCreatePage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState([]);
  const history = useHistory();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // 准备请求数据
      const issueData = {
        title: values.title,
        description: values.description,
        type: values.type,
        category: values.category,
        priority: values.priority
      };
      
      // 如果有关联案例，添加到数据中
      if (values.related_case) {
        issueData.matched_case_id = values.related_case;
      }
      
      const response = await api.post('/issues', issueData);
      console.log('创建问题成功:', response.data);
      message.success('问题创建成功');
      history.push('/issues');
    } catch (error) {
      console.error('问题创建失败:', error);
      
      // 如果错误已经被拦截器处理过（如401认证错误），则不再显示错误消息
      if (error.handled) {
        return;
      }
      
      if (error.response) {
        // 服务器响应了错误
        const errorMessage = error.response.data?.detail || '问题创建失败，请稍后重试';
        message.error(errorMessage);
      } else if (error.request) {
        // 请求发出但没有收到响应
        message.error('网络错误，请检查网络连接');
      } else {
        // 其他错误
        message.error('问题创建失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };

  const handleUpload = ({ file, fileList }) => {
    setFileList(fileList);
    return false; // 阻止自动上传
  };

  return (
    <div>
      <h2>创建问题</h2>
      
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            type: 'customer',
            category: 'hardware',
            priority: 'medium'
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="问题标题"
                rules={[{ required: true, message: '请输入问题标题' }]}
              >
                <Input placeholder="简要描述问题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="问题类型"
                rules={[{ required: true, message: '请选择问题类型' }]}
              >
                <Select>
                  <Option value="customer">
                    <CustomerServiceOutlined /> 客户问题
                  </Option>
                  <Option value="internal">
                    <BugOutlined /> 内部问题
                  </Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="问题描述"
            rules={[{ required: true, message: '请输入问题详细描述' }]}
          >
            <TextArea 
              rows={6} 
              placeholder="请详细描述问题现象、复现步骤、环境信息等" 
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="category"
                label="问题分类"
                rules={[{ required: true, message: '请选择问题分类' }]}
              >
                <Select>
                  <Option value="hardware">硬件</Option>
                  <Option value="software">软件</Option>
                  <Option value="firmware">固件</Option>
                  <Option value="network">网络</Option>
                  <Option value="other">其他</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="priority"
                label="优先级"
                rules={[{ required: true, message: '请选择优先级' }]}
              >
                <Select>
                  <Option value="low">低</Option>
                  <Option value="medium">中</Option>
                  <Option value="high">高</Option>
                  <Option value="urgent">紧急</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="related_case"
                label="关联案例"
              >
                <Select
                  showSearch
                  placeholder="搜索关联案例"
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option value="1">设备无法启动</Option>
                  <Option value="2">软件界面无响应</Option>
                  <Option value="3">网络连接不稳定</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="attachments"
            label="附件"
            valuePropName="fileList"
            getValueFromEvent={normFile}
          >
            <Upload 
              name="attachments" 
              fileList={fileList}
              onChange={handleUpload}
              beforeUpload={() => false} // 阻止自动上传
            >
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} icon={<PlusOutlined />}>
              创建问题
            </Button>
            <Button 
              style={{ marginLeft: 8 }}
              onClick={() => history.push('/issues')}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default IssueCreatePage;